package com.chexiehui.jc.ui.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusLinearLayout;
import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.Glide;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpFragment;
import com.chexiehui.jc.base.BaseMvpLazyLoadFragment;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.BrandInfo;
import com.chexiehui.jc.entity.BrandListInfo;
import com.chexiehui.jc.entity.CarSeriesInfo;
import com.chexiehui.jc.mvp.car.CarGarageEnergyCovenant;
import com.chexiehui.jc.mvp.car.CarGarageEnergyPresenter;
import com.chexiehui.jc.ui.activity.CarSeriesDetailsActivity;
import com.chexiehui.jc.ui.activity.CarBrandSaleListActivity;
import com.chexiehui.jc.ui.activity.SearchActivity;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.LoadingLayout;
import com.chexiehui.jc.widget.NonSlidingGridView;
import com.chexiehui.jc.widget.indexbar.IndexBar;
import com.chexiehui.jc.widget.indexbar.suspension.SuspensionDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: SongJun.
 * CreateDate: 2019/1/21 0021.
 * Description: 新能源
 */

public class CarGarageEnergyFragment extends BaseMvpLazyLoadFragment<CarGarageEnergyPresenter> implements CarGarageEnergyCovenant.View {

    public static CarGarageEnergyFragment getInstance() {
        CarGarageEnergyFragment fragment = new CarGarageEnergyFragment();
        return fragment;
    }

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.ll_head_search)
    RadiusLinearLayout llHeadSearch;
    @BindView(R.id.nsgv_head_recommend_car)
    NonSlidingGridView nsgvHeadRecommendCar;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.ib_right_index_bar)
    IndexBar ibRightIndexBar;
    @BindView(R.id.tv_side_bar_hint)
    TextView tvSideBarHint;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;

    private com.zhy.adapter.recyclerview.CommonAdapter<BrandInfo> carBrandAdapter;
    private List<BrandInfo> brandListData;
    private SuspensionDecoration suspensionDecoration;
    private List<CarSeriesInfo> hotSeriesData;
    private CommonAdapter<CarSeriesInfo> hotSeriesAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_car_garage_energy;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setEnableOverScrollDrag(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setEnableOverScrollDrag(true);
        refreshLayout.setDragRate(0.5f);
        ibRightIndexBar.setVisibility(View.GONE);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            mvpPresenter.getHotSeriesList();
            mvpPresenter.getBrandList();
        });

        loadingLayout.setOnReloadListener(v -> {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getHotSeriesList();
            mvpPresenter.getBrandList();
        });

        hotSeriesData = new ArrayList<>();
        nsgvHeadRecommendCar.setAdapter(hotSeriesAdapter = new CommonAdapter<CarSeriesInfo>(mActivity, R.layout.item_car_garage_energy_recommend_car, hotSeriesData) {
            @Override
            protected void convert(ViewHolder viewHolder, CarSeriesInfo item, int position) {
                GlideUtil.loadImageViewCrop(mContext, item.getImg(), viewHolder.getView(R.id.iv_item_icon), R.drawable.shape_square, R.drawable.shape_square);
                viewHolder.setText(R.id.tv_item_name, item.getName());
            }
        });
        nsgvHeadRecommendCar.setOnItemClickListener((parent, view, position, id) -> {
            if(NoDoubleClickUtils.isDoubleClick()) return;
            startActivity(CarSeriesDetailsActivity.class,
                    new BundleBuilder().putString("seriesId", hotSeriesData.get(position).getId())
                            .create());
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        recycler.setLayoutManager(layoutManager);
        brandListData = new ArrayList<>();
        carBrandAdapter = new com.zhy.adapter.recyclerview.CommonAdapter<BrandInfo>(mActivity, R.layout.item_car_garage_new_brand, brandListData) {
            @Override
            protected void convert(com.zhy.adapter.recyclerview.base.ViewHolder holder, BrandInfo brandInfo, int position) {
                holder.setText(R.id.tv_item_name, brandInfo.getName());
                Glide.with(mActivity)
                        .load(brandInfo.getImg())
                        .into((ImageView) holder.getView(R.id.iv_item_icon));
            }
        };
        carBrandAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if(NoDoubleClickUtils.isDoubleClick()) return;
                startActivity(CarBrandSaleListActivity.class,
                        new BundleBuilder()
                                .putSerializable("entity", brandListData.get(position))
                                .putString("energy", "3")
                                .create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        recycler.setAdapter(carBrandAdapter);
        suspensionDecoration = new SuspensionDecoration(mActivity, brandListData);
        recycler.addItemDecoration(suspensionDecoration);
        //indexbar初始化
        ibRightIndexBar.setmPressedShowTextView(tvSideBarHint)//设置HintTextView
                .setNeedRealIndex(false)//设置需要真实的索引
                .setSourceDatasAlreadySorted(true)
                .setmLayoutManager(layoutManager);//设置RecyclerView的LayoutManager
        isPrepared = true;
        lazyLoad();
    }

    @OnClick({R.id.ll_head_search})
    public void onViewClicked(View view){
        switch (view.getId()){
            case R.id.ll_head_search:
                startActivity(SearchActivity.class);
                break;
        }
    }

    @Override
    protected void lazyLoad() {
        if(!isVisible || !isPrepared || mHasLoadedOnce){
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getHotSeriesList();
        mvpPresenter.getBrandList();
    }

    @Override
    protected CarGarageEnergyPresenter createPresenter() {
        return new CarGarageEnergyPresenter(this);
    }

    @Override
    public void onGetHotSeriesListSuccess(BaseModel<BasePage<CarSeriesInfo>> successResult) {
        hotSeriesData.clear();
        hotSeriesData.addAll(successResult.getData().getItems());
        hotSeriesAdapter.notifyDataSetChanged();
        nsgvHeadRecommendCar.setNumColumns(hotSeriesData.size());
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvHeadRecommendCar.getLayoutParams();
        lp.width = SizeUtils.dp2px(110) * hotSeriesData.size() + SizeUtils.dp2px(10) * (hotSeriesData.size() - 1);
        nsgvHeadRecommendCar.setLayoutParams(lp);
    }

    @Override
    public void onGetHotSeriesListFailure(BaseModel<Object> failureResult) {
        if(failureResult.getResultCode() == Constants.PAGE_DATA_EMPTY){
            hotSeriesData.clear();
            hotSeriesAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetBrandListSuccess(BaseModel<List<BrandListInfo>> successResult) {
        mHasLoadedOnce = true;
        if(refreshLayout.getState() == RefreshState.Refreshing){
            refreshLayout.finishRefresh(true);
        }
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        ibRightIndexBar.setVisibility(View.VISIBLE);
        List<BrandInfo> list = new ArrayList<>();
        for (int i = 0; i < successResult.getData().size(); i++) {
            for (int j = 0; j < successResult.getData().get(i).getBrands().size(); j++) {
                successResult.getData().get(i).getBrands().get(j).setSpell(successResult.getData().get(i).getSpell());
            }
            list.addAll(successResult.getData().get(i).getBrands());
        }
        brandListData.clear();
        brandListData.addAll(list);
        carBrandAdapter.notifyDataSetChanged();
        ibRightIndexBar.setmSourceDatas(brandListData)//设置数据
                .invalidate();
        suspensionDecoration.setmDatas(brandListData);
    }

    @Override
    public void onGetBrandListFailure(BaseModel<Object> failureResult) {
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if(refreshLayout.getState() == RefreshState.Refreshing){
            refreshLayout.finishRefresh(true);
        }
        ibRightIndexBar.setVisibility(View.GONE);
        if(refreshLayout.getState() == RefreshState.Refreshing){
            refreshLayout.finishRefresh(false);
        }
    }

}
